package pe.org.jhsystem.consola.pdf;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 *
 * @author jhuamanv
 */
public class PdfMain {

    public static void main(String[] args) throws DocumentException, FileNotFoundException, IOException{
        //onlyText();
        marcaDeAgua();
    }

    public static void onlyText() throws DocumentException, FileNotFoundException{
        Document document = new Document();
        PdfWriter.getInstance(document,new FileOutputStream("onlyText.pdf")).setInitialLeading(20);
        document.open();
        //Agregando texto simple
        document.add(new Paragraph("Cadena de caracteres en el PDF"));
        //Agregando texto con formato.
        document.add(new Paragraph("Este es el segundo y tiene una fuente rara",
				FontFactory.getFont("arial",   // fuente
				22,                            // tamaño
				Font.ITALIC,                   // estilo
				BaseColor.CYAN)));             // color
        //Agregando imagen
        try{
            Image foto = Image.getInstance("duke.jpg");
            foto.scaleToFit(100, 100);
            foto.setAlignment(Chunk.ALIGN_MIDDLE);
            document.add(foto);
        }catch(Exception e){
            e.printStackTrace();
        }
        //Agregando una tabla
        PdfPTable tabla = new PdfPTable(3);
        for (int i = 0; i < 15; i++) tabla.addCell("celda " + i);
        document.add(tabla);

        document.close();
    }

    public static void marcaDeAgua() throws IOException, DocumentException{
        String path = "onlyText.pdf";
        PdfReader reader = new PdfReader(path);
        FileOutputStream fs = null;
        PdfStamper stamp = null;
        Document document = null;
        try{
            document = new Document();
            String outputPdf = String.format("temp%s.pdf","GuiaConsola");
            fs = new FileOutputStream(outputPdf);
            stamp = new PdfStamper(reader, fs);
            BaseFont bf = BaseFont.createFont();// @"c:\windows\fonts\arial.ttf",BaseFont.CP1252, true);
            PdfGState gs = new PdfGState();
            gs.setFillOpacity(0.35F);
            gs.setStrokeOpacity(0.35F);
            for (int nPag = 1; nPag <= reader.getNumberOfPages(); nPag++){
                Rectangle tamPagina = reader.getPageSizeWithRotation(nPag);
                PdfContentByte over = stamp.getOverContent(nPag);
                over.beginText();
                WriteTextToDocument(bf,tamPagina,over,gs,"jhsystem.org.pe");
                over.endText();
            }
        }finally{
            // Garantizamos que aunque falle se cierran los objetos
            // alternativa:usar using
            reader.close();
            if (stamp != null) stamp.close();
            if (fs != null) fs.close();
            if (document != null) document.close();
        }
        System.out.println("Fin de ejecucion");
    }

    private static void WriteTextToDocument( BaseFont bf, Rectangle tamPagina, PdfContentByte over, PdfGState gs, String texto){
        over.setGState(gs);
        over.setRGBColorFill(220, 220, 220);
        over.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_STROKE);
        over.setFontAndSize(bf, 46);
        float anchoDiag = (float)Math.sqrt(Math.pow((tamPagina.getHeight() - 120), 2) + Math.pow((tamPagina.getWidth() - 60), 2));
        float porc = (float) 100 * (anchoDiag / bf.getWidthPoint(texto, 46));
        over.setHorizontalScaling(porc);
        double angPage = (-1)* Math.atan((tamPagina.getHeight() - 60) / (tamPagina.getWidth() - 60));
        over.setTextMatrix( (float)Math.cos(angPage),(float)Math.sin(angPage),(float)((-1F) * Math.sin(angPage)),(float)Math.cos(angPage),30F,(float)tamPagina.getHeight() - 60);
        over.showText(texto);
    }

}
